#! /usr/bin/python
# -*- coding: UTF-8 -*-

import os, sys
import shutil
import time
import codecs
import argparse
import shutil

reload(sys)

sys.setdefaultencoding("utf-8")


class RebuildBase(object):
    def __init__(self):
        pass

    def runTask(self, curPath):
        pass


class RebuildHeaderTool(RebuildBase):

    def runTask(self, curPath):

        headersPath = curPath + os.sep + 'Headers'
        if os.path.exists(headersPath):
            shutil.rmtree(headersPath)
        os.mkdir(headersPath)

        list = []
        self.listDir(curPath, list)
        list = self.filterExtName(list, '.h')

        cmd = ''
        for path in list:
            # path = ''
            fileName = path[path.rfind(os.sep) + 1:]
            linkPath = headersPath + os.sep + fileName
            srcPath = path
            self.makeCmdLink(linkPath, srcPath, curPath, headersPath)
        print("重置主工程索引成功")
        return [headersPath]
        #     oneCmd = "ln" + " " + "-s" + " " + srcPath + " " + linkPath
        #     cmd = cmd + " " + oneCmd
        # print(cmd)
        # os.system(cmd)

    # 生成替身
    def makeCmdLink(self, tarPath, srcPath, curPath, headersPath):

        srcPath = ".." + srcPath.replace(curPath, "")
        oneCmd = "ln" + " " + "-s" + " " + srcPath + " " + tarPath
        cdCmd = "cd " + headersPath

        cmd = cdCmd + "&&" + oneCmd
        # print(cmd)
        os.system(oneCmd)
        pass

    # 过滤指定后缀名
    def filterExtName(self, list, extName):
        rstList = []
        for text in list:
            if text.lower().rfind(extName.lower()) > 0:
                rstList.append(text)
        return rstList

    # 递归文件
    def listDir(self, path, list_name):  # 传入存储的list
        for file in os.listdir(path):
            file_path = os.path.join(path, file)
            if os.path.isdir(file_path):
                self.listDir(file_path, list_name)
            else:
                list_name.append(file_path)


class RebuildPodTool(RebuildBase):

    def runTask(self, curPath):
        list = []
        self.listDir(curPath, list)
        headersPath = []
        for path in list:
            folder_path = path[0:path.rfind(os.sep)]
            if folder_path in headersPath or folder_path == path:
                pass
            else:
                headersPath.append(folder_path)
        print("获取POD引用路径成功")
        return headersPath

    def listDir(self, path, list_name):
        for file in os.listdir(path):
            file_path = os.path.join(path, file)
            if os.path.isdir(file_path):
                self.listDir(file_path, list_name)
            else:
                list_name.append(file_path)


class RebuildProject(RebuildBase):
    def runTask(self, sub_module_path, headersPathList):

        # cmd = "/usr/libexec/Plistbuddy - c 'Set :Software:Gallery:Version "1.1"' ~/Desktop/com.sample.plist"
        text = ''
        for path in headersPathList:
            text = text + "\"" + path + "\"" + ',' + "\n"
            # text = text + path + ','

        # cmd = "/usr/libexec/Plistbuddy - c 'Set:0B9F2A9E1D24EC9A00136C8B:buildSettings:HEADER_SEARCH_PATHS " + "\"" +  text + "\" \' " + sub_module_path
        # print(cmd)
        # os.system(cmd)

        file_object = open(sub_module_path,"r+")
        try:
            file_context = file_object.read()
            list =  file_context.split("HEADER_SEARCH_PATHS");
            if len(list) > 2:
                startText = list[0]
                debugText =  list[1]
                releaseText = list[2]
                debugText = debugText[debugText.find(");"):]
                debugText = "HEADER_SEARCH_PATHS = (\n" + text  + debugText
                releaseText = releaseText[releaseText.find(");"):]
                releaseText = "HEADER_SEARCH_PATHS = (\n" + text  + releaseText
                rstText = startText + debugText + releaseText
                file_object.close()
                os.remove(sub_module_path)

                file_object = open(sub_module_path, "w")
                file_object.seek(0)
                file_object.write(rstText);
                file_object.close()
            else:
                list = file_context.split("CODE_SIGN_STYLE");
                startText = list[0]
                debugText = list[1]
                releaseText = list[2]
                search_path = "HEADER_SEARCH_PATHS = (\n" + text + "\n)"
                debugText = "CODE_SIGN_STYLE " + debugText[debugText.find("="):]
                debugText = debugText[:debugText.find(";")] + ";\n" + search_path + debugText[debugText.find(";"):]

                releaseText = "CODE_SIGN_STYLE " + releaseText[releaseText.find("="):]
                releaseText = releaseText[:releaseText.find(";")] + ";\n" + search_path + releaseText[releaseText.find(";"):]
                rstText = startText + debugText + releaseText

                file_object.close()
                os.remove(sub_module_path)

                file_object = open(sub_module_path, "w")
                file_object.seek(0)
                file_object.write(rstText);
                file_object.close()
            print("重建索引成功" + sub_module_path)
        except:
            print("重建索引失败" + sub_module_path)
        finally:
            pass

# ----------------------------------------------------main------------------------------------------------
def parse_args():
    global script_path, proj_ios_path
    parser = argparse.ArgumentParser(description='模块重建索引脚本.\n')
    parser.add_argument('--rebuild_folder_name', dest='rebuild_folder_name', type=str, required=False, default="",
                        help='需要重建索引的文件夹名字,该文件夹必须与脚本在同级目录')
    parser.add_argument('--main_project_dir', dest='main_project_dir', type=str, required=False, default="",
                        help='主项目相对于工程路径')
    args = parser.parse_args()
    return args


def main():
    startTime = time.time()


    global headersPathList

    app_args = parse_args()
    rebuild_folder_name = app_args.rebuild_folder_name
    main_project_dir = app_args.main_project_dir

    rebuild_folder_name = "TouchTV-Report"
    main_project_dir = 'TouchTV-Report.xcodeproj/project.pbxproj'
    pod_public_folder_name = "Pods/Headers/Public"
    pod_private_folder_name = "Pods/Headers/Private"
    sub_module_list = ['ModuleMine/ModuleMine.xcodeproj/project.pbxproj','ModuleSquare/ModuleSquare.xcodeproj/project.pbxproj']

    workSpacePath = os.getcwd()

    # sub_module_path = workSpacePath + os.sep + sub_module_list[0]
    # projectTool = RebuildProject()
    # projectTool.runTask(sub_module_path, [])

    # 执行重建索引脚本
    if len(rebuild_folder_name) > 0:
        indexTool = RebuildHeaderTool()
        curPath = workSpacePath + os.sep + rebuild_folder_name
        if os.path.exists(curPath):
            headersPathList = indexTool.runTask(curPath)

    # 重建POD public索引
    podPath = workSpacePath + os.sep + pod_public_folder_name
    if os.path.exists(podPath):
        podTool = RebuildPodTool()
        list = podTool.runTask(podPath)
        for tmp in list:
            if tmp != podPath:
                headersPathList.append(tmp)

    # 重建POD private索引
    podPath = workSpacePath + os.sep + pod_private_folder_name
    if os.path.exists(podPath):
        podTool = RebuildPodTool()
        list = podTool.runTask(podPath)
        for tmp in list:
            if tmp != podPath:
                headersPathList.append(tmp)

    # 获取重建列表
    rebuildList = []
    for tmp in headersPathList:
        aa = tmp.replace(workSpacePath, '$(SRCROOT)/..')
        rebuildList.append(aa)
        print("\"" + aa + "\"" + ',')

    # 重建项目
    for sub_module_path in sub_module_list:
        sub_module_path = workSpacePath + os.sep + sub_module_path
        if os.path.exists(sub_module_path):
            projectTool = RebuildProject()
            projectTool.runTask(sub_module_path, rebuildList)



    endTime = time.time()
    print("总耗时: %0.2f" % (endTime - startTime))


if __name__ == "__main__":
    main()
